<!-- 验收 -->
<template>
  <el-container style="height: 100%;">
    <!-- 筛选条件 -->
    <el-header style="height: 9vh;">
      <!-- 字段搜索 -->
      <el-row class="search-head" :gutter="12" justify="space-between">
        <el-col :span="7" style="display: flex;">
          <span class="search">工程编号：</span>
          <el-input placeholder="请输入工程编号" v-model="keyword" style="width: 200px;"></el-input>
        </el-col>
        <el-col :span="9" style="display: flex;">
          <span class="search">完成时间：</span>
          <el-date-picker v-model="finishTimes" value-format="YYYY-MM-DD" @change="handleOnDateChange"
            type="daterange" range-separator="至" start-placeholder="起始时间" end-placeholder="结束时间" />
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="handleOnSearch">
            <el-icon>
              <Search />
            </el-icon>
            查询
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button @click="handleOnReSet">重置</el-button>
        </el-col>
        <el-col :span="2">
          <el-button link type="primary" @click="handleOnOpenAdv">
            展开
            <el-icon>
              <arrow-down />
            </el-icon>
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="handleOnStatistic">
            统计
          </el-button>
        </el-col>
        <div class="adv-search" v-if="isShowAdvSearch">
          <el-row justify="space-between" style="background-color: #f5f7fa; padding: 6px 0;">
            <el-col :span="4">
              <span style="font-size: 16px; padding: 10px">高级搜索</span>
            </el-col>
            <el-col :span="1">
              <el-button type="text" link @click="isShowAdvSearch = false">
                <el-icon>
                  <Close />
                </el-icon>
              </el-button>
            </el-col>
          </el-row>
          <el-row :key="item.field" justify="space-between" v-for="(item, index) in searchQurry.field_map_operates.slice(1)"
            style="padding: 8px 0 0 2.5%;">
            <el-col :span="8">
              <el-select v-model="item.field" placeholder="请选择字段" style="width: 100%;">
                <el-option v-for="opt in options" :key="opt.name" :label="opt.caption" :value="opt.name" />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="item.operate" placeholder="请选择匹配方式">
                <el-option v-for="opt in operations" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-col>
            <el-col :span="10">
              <el-select v-if="item.field && getTypeOfField(item.field).includes('TEXT') && item.operate !== 'contains'"
                v-model="item.value" filterable remote reserve-keyword placeholder=""
                :remote-method="(val) => handleOnSearchFields(item.field, val)" :loading="loading">
                <el-option v-for="item in fieldOptions" :key="item" :label="item" :value="item" />
              </el-select>
              <el-input v-else v-model="item.value" placeholder=""></el-input>
            </el-col>
            <el-col :span="1">
              <el-button text @click="handleOnDeleteField(index)">
                <el-icon>
                  <CircleCloseFilled />
                </el-icon>
              </el-button>
            </el-col>
          </el-row>
          <div style="padding: 12px 0;">
            <el-row justify="center">
              <el-button style="width: 95%;" @click="handleOnAddFields">
                <el-icon>
                  <Plus />
                </el-icon>增加
              </el-button>
            </el-row>
          </div>
        </div>
      </el-row>

      <el-row style="padding: 10px 0; height: 40px;">
        <!-- <el-col :span="3" style="margin-top: -15px; margin-left: 13px;"><span
            style="font-size: 14px; color: black;">空间查询:</span></el-col> -->
        <el-col :span="24" style="background-color: #f5f7fa;">
          <el-tabs v-model="activeNames" style="width: 100%; height: 100%;" @tab-click="handleTabClick">
            <el-tab-pane label="行政区" name="1">
              <div class="xzqcx" style="position: relative;z-index: 10; margin-top: -10px;">
                <div class="xzqcxtj">
                  <div>
                    <!-- <span>县级：</span> -->
                    <div>
                      <el-select disabled v-model="selectXZQ.selectsj" placeholder="白云区">
                        <el-option label="白云区" value="1"></el-option>
                      </el-select>
                    </div>
                  </div>
                  <div>
                    <!-- <span>街镇：</span> -->
                    <div>
                      <el-select v-model="selectXZQ.selectxj" placeholder="街镇" @change="jiezhenC">
                        <!-- <el-option label="街镇" value="1"></el-option> -->
                        <el-option v-for="item in jiezhen" :key="item.xzqmc" :label="item.jdmc"
                          :value="item.jdmc"></el-option>
                      </el-select>
                    </div>
                  </div>
                  <div>
                    <!-- <span>村居委：</span> -->
                    <div>
                      <el-select v-model="selectXZQ.selectcjw" placeholder="村居委" @change="cunjuWC">
                        <!-- <el-option label="村居委" value="1"></el-option> -->
                        <el-option v-for="item in cunjuW" :key="item.xzqmc" :label="item.xzqmc"
                          :value="item.xzqmc"></el-option>
                      </el-select>
                    </div>
                  </div>
                  <div>
                    <!-- <el-button size="small" @click="fwchaXun" type="primary">查询</el-button> -->
                    <el-button @click="fwclear" type="primary">清除</el-button>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="自定义区域" name="2">
              <div class="xzqcx" style="position: relative;z-index: 10; margin-top: -20px;">
                <div class="xzqcxtj">
                  <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                    <div style="display: flex; width: 300px; justify-content: space-between; align-items: center;">
                      <el-upload ref="upload" class="upload-demo" :file-list="shpFileList" :action="uploadShp"
                        name="shpFile" :limit="1" :on-success="handleOnUploadShpSuccess"
                        :on-change="(e) => handleOnUploadChange('shp', e)" :show-file-list="false">
                        <template #trigger>
                          <el-button type="primary">上传shp</el-button>
                        </template>
                      </el-upload>
                      <el-upload ref="upload" class="upload-demo" :file-list="cadFileList"
                        action="http://192.168.88.177:8002/elupload/online/api/upload/" name="files" :limit="1"
                        :data="updateParams" :on-exceed="handleExceed" :on-success="handleOnUploadSuccess"
                        :on-change="(e) => handleOnUploadChange('cad', e)" :show-file-list="false">
                        <template #trigger>
                          <el-button type="primary">上传cad</el-button>
                        </template>
                      </el-upload>
                      <el-button style="margin-top: 16px;" type="primary" @click="handleOnDraw">手绘范围</el-button>
                    </div>
                    <div class="customUploadStatus">

                    </div>
                    <div style="width: auto; margin-right: 20px; margin-top: 6px;">
                      <el-button type="primary" @click="handleOnCustomClear">清除</el-button>
                    </div>
                  </div>
                </div>
              </div>

            </el-tab-pane>
          </el-tabs>
        </el-col>

      </el-row>
    </el-header>
    <!-- 列表 -->
    <el-main style="height: 75vh; overflow-y: auto; --el-main-padding: 0 20px;">
      <el-table v-loading="tableLoading" :data="tableData" style="width: 100%;" @row-click="handleOnRowClick"
        @sort-change="handleOnSortChange" height="75vh">
        <el-table-column sortable="custom" prop="gcbh" show-overflow-tooltip label="工程编号" width="130" />
        <el-table-column sortable="custom" prop="xmmc" show-overflow-tooltip label="建设项目名称" width="160" />
        <el-table-column sortable="custom" prop="fxah" show-overflow-tooltip label="放线案号" width="130" />
        <el-table-column sortable="custom" prop="jsgcghxkz" show-overflow-tooltip label="建设工程规划许可证号" width="200" />
        <el-table-column sortable="custom" prop="xgpwh" show-overflow-tooltip label="相关批文号" width="120" />
        <el-table-column sortable="custom" prop="fwgn" show-overflow-tooltip label="主要功能" width="150" />
        <el-table-column sortable="custom" prop="zygnjzmj" label="主要功能建筑面积" width="180" />
        <el-table-column sortable="custom" prop="gnlb" label="功能类别" width="150" />
        <el-table-column sortable="custom" prop="jsgm" label="建设规模" width="120" />
        <el-table-column sortable="custom" prop="jdmj" label="基底面积" width="120" />
        <el-table-column sortable="custom" prop="hs" label="住宅户数" width="120" />
        <el-table-column sortable="custom" prop="cw" label="汽车泊位（个）" width="150" />
        <el-table-column sortable="custom" prop="zjzmj" label="总建筑面积（m2）" width="170" />
        <el-table-column sortable="custom" prop="dsmj" label="地上面积（m2）" width="160" />
        <el-table-column sortable="custom" prop="dxmj" label="地下面积（m2）" width="160" />
        <el-table-column sortable="custom" prop="jzgd" label="建筑高度（m）" width="150" />
        <el-table-column sortable="custom" prop="jzjg" label="建筑结构" width="120" />
        <el-table-column sortable="custom" prop="jsdw" show-overflow-tooltip label="建设单位" width="120" />
        <el-table-column sortable="custom" prop="jswz" show-overflow-tooltip label="建设位置" width="120" />
        <el-table-column sortable="custom" prop="dscs" label="地上层数" width="120" />
        <el-table-column sortable="custom" prop="dxcs" label="地下层数" width="120" />
        <el-table-column sortable="custom" show-overflow-tooltip label="完成时间" width="120">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px">{{ scope.row.wcsj.slice(0, 10) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column sortable="custom" prop="bz" show-overflow-tooltip label="备注" width="120" />
      </el-table>
    </el-main>
    <!-- 底部 -->
    <el-footer style="position:absolute; bottom: 0; width: 95%;">
      <el-row justify="end" align="top" style="gap: 20px;">
        <el-pagination background layout="total, prev, pager, next" @current-change="hanldeOnPageChange"
          :page-size="searchQurry.page_size" :total="totalData" />
        <el-button type="primary" @click="handleOnExportTable">导出台账</el-button>
      </el-row>
    </el-footer>
  </el-container>
  <el-dialog v-model="dialogVisible" title="验收" width="800">
    <el-descriptions :column="2" border>
      <el-descriptions-item label="工程编号" align="center">
        {{ featureData.gcbh }}
      </el-descriptions-item>
      <el-descriptions-item label="建设项目名称" align="center">
        {{ featureData.xmmc }}
      </el-descriptions-item>
      <el-descriptions-item label="放线案号" align="center">
        {{ featureData.fxah }}
      </el-descriptions-item>
      <el-descriptions-item label="建设工程规划许可证号" align="center">
        {{ featureData.jsgcghxkz }}
      </el-descriptions-item>
      <el-descriptions-item label="相关批文号" align="center">
        {{ featureData.xgpwh }}
      </el-descriptions-item>
      <el-descriptions-item label="主要功能" align="center">
        {{ featureData.fwgn }}
      </el-descriptions-item>
      <el-descriptions-item label="建设规模" align="center">
        {{ featureData.jsgm }}
      </el-descriptions-item>
      <el-descriptions-item label="基底面积" align="center">
        {{ featureData.jdmj }}
      </el-descriptions-item>
      <el-descriptions-item label="住宅户数" align="center">
        {{ featureData.hs }}
      </el-descriptions-item>
      <el-descriptions-item label="汽车泊位（个）" align="center">
        {{ featureData.cw }}
      </el-descriptions-item>
      <el-descriptions-item label="总建筑面积（M²c）" align="center">
        {{ featureData.zjzmj }}
      </el-descriptions-item>
      <el-descriptions-item label="建筑高度（m）" align="center">
        {{ featureData.jzgd }}
      </el-descriptions-item>
      <el-descriptions-item label="地上面积（M²）" align="center">
        {{ featureData.dsmj }}
      </el-descriptions-item>
      <el-descriptions-item label="地下面积（M²）" align="center">
        {{ featureData.dxmj }}
      </el-descriptions-item>
      <el-descriptions-item label="建筑结构" align="center">
        {{ featureData.jzjg }}
      </el-descriptions-item>
      <el-descriptions-item label="建设单位" align="center">
        {{ featureData.jsdw }}
      </el-descriptions-item>
      <el-descriptions-item label="建设位置" align="center">
        {{ featureData.jswz }}
      </el-descriptions-item>
      <el-descriptions-item label="地上层数" align="center">
        {{ featureData.dscs }}
      </el-descriptions-item>
      <el-descriptions-item label="地下层数" align="center">
        {{ featureData.dxcs }}
      </el-descriptions-item>
      <el-descriptions-item label="完成时间" align="center">
        {{ featureData.wcsj }}
      </el-descriptions-item>
      <el-descriptions-item label="备注" align="center">
        {{ featureData.bz }}
      </el-descriptions-item>
    </el-descriptions>
  </el-dialog>
</template>

<script setup>
import { Search, ArrowDown, Close, Plus, CircleCloseFilled } from '@element-plus/icons-vue';
import { reactive, ref, onMounted } from 'vue';
import { getYSFields } from '@/api/info';
import { getJieDaoZ, getCSQByJD, getGeomByAddress } from '@/api/xzqh';
import { getGUID, wktStrToGeoJson, geoJsonToWktStr } from "@/utils/tool";
import { Draw } from "@/utils/draw";
import { useStore } from '@/store/useStore';
import { uploadShp, runFme, getFmeRange, getResultPage, getDataForSmid, getProjectRangeGeometry, getQueryOperationEnumList, getSearchList, exportProjectResultExcel } from '@/api/dataApi';
import { ElMessage } from 'element-plus';
import { YanshouMap } from '@/assets/yanshouMap';

const pageName = '工程成果_验收';

const store = useStore();

function getDefaultState() {
  return {
    field_map_operates: [
      {
        field: "gcbh",
        operate: 'contains',
        value: ""
      },
    ],
    page_no: 1,
    page_size: 30,
    wcsj_end_time: "",
    wcsj_start_time: "",
    wkt_cad_range: "",
    wkt_district: "",
    wkt_range: "",
    wkt_shp_range: [],
    table_name: pageName
  };
}

const searchQurry = reactive(getDefaultState())

const totalData = ref(0);

const tableLoading = ref(false);

const handleOnSearch = () => {
  searchQurry.page_no = 1;
  loadTableData();
};

const handleOnDateChange = () => {
  searchQurry.wcsj_start_time = finishTimes.value[0];
  searchQurry.wcsj_end_time = finishTimes.value[1];
}

const hanldeOnPageChange = (val) => {
  searchQurry.page_no = val;
  loadTableData();
}


/**
 * 对数据进行格式化处理
 *
 * @param {Array} data - 包含多个对象的数组，每个对象具有 'field' 和 'value' 属性
 * @returns {void} 无返回值
 *
 * @description
 * 该函数遍历传入的 `data` 数组，检查每个对象的 `field` 属性的类型。
 * 如果 `field` 属性的类型是整数（INT）或浮点数（DOUBLE），则将其 `value` 属性转换为数字类型。
 */
const formateData = (data) => {
  for (let i = 0; i < data.length; i++) {
    if (getTypeOfField(data[i].field)?.includes('INT') || getTypeOfField(data[i].field)?.includes('DOUBLE')) {
      data[i].value = Number(data[i].value)
    }
  }
}

// 重置
const handleOnReSet = () => {
  draw.clearDraw();
  Object.assign(searchQurry, getDefaultState());
  finishTimes.value = ['', ''];
  keyword.value = '';
  loadTableData();
}

// 列表查询
const loadTableData = async (loadMap = true) => {
  searchQurry.field_map_operates = searchQurry.field_map_operates.filter(item => item.operate !== '');
  // if (keyword.value) {
  //   searchQurry.field_map_operates.push({
  //     field: "gcbh",
  //     operate: 'contains',
  //     value: keyword.value
  //   })
  // } else {
  //   searchQurry.field_map_operates = searchQurry.field_map_operates.filter(item => !(item.field === "gcbh" && item.operate === 'equals'))
  // }
  searchQurry.field_map_operates[0].value = keyword.value;
  formateData(searchQurry.field_map_operates);
  if (draw.geoJson) {
    // eslint-disable-next-line no-undef
    let geometry = L.polygon(draw.geom);
    // eslint-disable-next-line no-undef
    var geo = L.Util.transform(geometry, L.CRS.EPSG4326, window.GZ2000);
    searchQurry.wkt_range = geoJsonToWktStr(geo.geometry);
  }

  tableLoading.value = true;
  await getResultPage(searchQurry).then(res => {
    tableData.value = res.data.data.list;
    console.log(tableData.value);
    totalData.value = res.data.data?.pagination?.total;
    tableLoading.value = false;
  }).catch(err => {
    ElMessage.error(err);
    tableLoading.value = false;
  })
  if (loadMap) {
    loadMapData();
  }
}

const tableData = ref([]);
const options = ref();
const loading = ref(false);
const fieldOptions = ref([]);
const selectXZQ = reactive({
  selectsj: '',
  selectxj: '',
  selectcjw: ''
})
const jiezhen = ref([])
const cunjuW = ref([]);
const jzcsqPlog = ref(null);
const finishTimes = ref('')
const draw = new Draw();
const keyword = ref('')
const activeNames = ref('0');

// 行政区
const jiezhenC = () => {
  getCSQByJD(selectXZQ.selectxj).then((res) => {
    cunjuW.value = res.data;
  });
  getGeomByAddress({
    name: 'JZ',
    jd: selectXZQ.selectxj,
  }).then((res) => {
    if (jzcsqPlog.value) {
      window.map.removeLayer(jzcsqPlog.value);
    }
    // wkt.value = res.data;
    searchQurry.wkt_district = res.data;
    var geo = JSON.parse(wktStrToGeoJson(searchQurry.wkt_district));
    console.log(geo);
    // eslint-disable-next-line no-undef
    var geoJ = L.geoJSON(geo);
    var style = {
      color: "red",
      fillColor: "rgb(123,180,255)",
      fillOpacity: 0.5,
    };
    // eslint-disable-next-line no-undef
    var pgeo = L.Util.transform(geoJ, GZ2000, L.CRS.EPSG4326);
    // eslint-disable-next-line no-undef
    jzcsqPlog.value = L.geoJSON(pgeo.features[0].geometry, style).addTo(window.map);
    window.map.fitBounds(jzcsqPlog.value.getBounds());
  });
}

const cunjuWC = () => {
  getGeomByAddress({
    name: "CSQ",
    csq: selectXZQ.selectcjw,
    jd: selectXZQ.selectxj,
  }).then(res => {
    if (jzcsqPlog.value) {
      window.map.removeLayer(jzcsqPlog.value);
    }
    searchQurry.wkt_district = res.data;
    var geo = JSON.parse(wktStrToGeoJson(searchQurry.wkt_district));
    // eslint-disable-next-line no-undef
    var geoJ = L.geoJSON(geo);
    var style = {
      color: "red",
      fillColor: "rgb(123,180,255)",
      fillOpacity: 0.5,
    };
    // eslint-disable-next-line no-undef
    var pgeo = L.Util.transform(geoJ, GZ2000, L.CRS.EPSG4326);
    // eslint-disable-next-line no-undef
    jzcsqPlog.value = L.geoJSON(pgeo.features[0].geometry, style).addTo(window.map);
    window.map.fitBounds(jzcsqPlog.value.getBounds());
  })
}

// 行政区划清除按钮
const fwclear = () => {
  if (jzcsqPlog.value) {
    window.map.removeLayer(jzcsqPlog.value);
  };
  searchQurry.wkt_district = '';
  selectXZQ.selectcjw = '';
  selectXZQ.selectxj = '';
}

// 空间查询按钮
const handleTabClick = (tab) => {
  if (tab.props.name === activeNames.value) {
    activeNames.value = '0';
  } else {
    if (tab.props.name === '1' && activeNames.value === '2') {
      handleOnCustomClear();
    } else if (tab.props.name === '2' && activeNames.value === '1') {
      fwclear();
    };
    activeNames.value = tab.props.name;
  }
};

// 上传文件
const shpFileList = ref([]);
const cadFileList = ref([]);
const updateParams = reactive({
  path: "D:\\Data\\uploadtemp",
  uuid: "",
});
const updateFileName = ref('');
const updateFileType = ref('');
const shpPlog = ref([])
const handleOnUploadShpSuccess = (res) => {
  res.data.forEach(item => {
    searchQurry.wkt_shp_range.push(item);
    var geo = JSON.parse(wktStrToGeoJson(item));
    // eslint-disable-next-line no-undef
    var geoJ = L.geoJSON(geo);
    var style = {
      color: "red",
      fillColor: "rgb(123,180,255)",
      fillOpacity: 0.5,
    };
    // eslint-disable-next-line no-undef
    var pgeo = L.Util.transform(geoJ, GZ2000, L.CRS.EPSG4326);
    // eslint-disable-next-line no-undef
    shpPlog.value.push(L.geoJSON(pgeo.features[0].geometry, style).addTo(window.map));
    window.map.fitBounds(shpPlog.value[0].getBounds());
  })
}

const handleExceed = () => {

}

const handleOnUploadSuccess = (e) => {
  console.log('upload success', e);
  exceedRunFme();
}

const exceedRunFme = () => {
  var paramValue = new Array();
  var paramName = ["uuid", "FanWeiXianName", "FanWeiXianFormat"];
  paramValue.push(updateParams.uuid);
  paramValue.push(updateFileName.value);
  paramValue.push(updateFileType.value);
  var paramNameJson = JSON.stringify(paramName);
  var paramValueJson = JSON.stringify(paramValue);
  runFme({
    modelName: 'file2pg2',
    paramValue: paramValueJson,
    paramName: paramNameJson,
  }).then(() => {
    getFmeRange(updateParams.uuid).then(res => {
      var json = JSON.parse(res.data[0].geom);
      addFwx(json, updateParams.uuid, updateFileName.value);
      updateParams.uuid = getGUID();
    })
  })
}
const cadPlog = ref(null)
const addFwx = (json) => {
  // eslint-disable-next-line no-undef
  var layer = L.geoJSON(json);
  var style = {
    color: "#ff0000",
    fillColor: "#ff0000",
    fillOpacity: 0.5,
    weight: 1,
    opacity: 1,
    fill: false,
    dashArray: null,
  };
  searchQurry.wkt_cad_range = geoJsonToWktStr(json);
  // eslint-disable-next-line no-undef
  var pgeo = L.Util.transform(layer, GZ2000, L.CRS.EPSG4326);
  // eslint-disable-next-line no-undef
  cadPlog.value = L.geoJSON(pgeo.features[0].geometry, style).addTo(
    window.map
  );
  window.map.fitBounds(cadPlog.value.getBounds());

}

const handleOnUploadChange = (type, e) => {
  switch (type) {
    case 'cad':
      updateFileName.value = e.name;
      updateFileType.value = 'DWG';
      break;
    case 'shp':
      updateFileName.value = e.name;
      updateFileType.value = 'SHP';
      break;
    default:
      break;
  }
};

const handleOnDraw = () => {
  draw.drawClick = false;
  draw.DrawPolygon();
}

const handleOnCustomClear = () => {
  draw.clearDraw();
  shpFileList.value = [];
  cadFileList.value = [];
  searchQurry.wkt_range = '';
  searchQurry.wkt_cad_range = '';
  searchQurry.wkt_shp_range = '';
  if (cadPlog.value) {
    console.log(cadPlog.value);
    window.map.removeLayer(cadPlog.value);
  }
  if (shpPlog.value.length > 0) {
    shpPlog.value.forEach(item => {
      window.map.removeLayer(item);
    })
  }
}

const operations = ref([]);

// 加载地图要素
const dialogVisible = ref(false);
const featureData = ref({});
const getFeatureDetail = (id) => {
  getDataForSmid({
    smid: id,
    table_name: pageName
  }).then(res => {
    featureData.value = res.data.data;
    dialogVisible.value = true;
  })
}

const loadMapData = () => {
  // window.map.eachLayer(function (layer) {
  //   console.log('search', layer);
  //   // if (!layer._url.includes('tianditu') || !layer._url.includes('2000年白云区影像_ZW2_V2014_gz2000x@2000年白云区影像_ZW2_V2014_gz2000x')) {
  //   //   layer.remove();
  //   // }
  // });
  getProjectRangeGeometry(searchQurry).then(res => {
    res.data.data.forEach(item => {
      var geo = JSON.parse(item.value);
      geo.properties = {
        name: item.key,
      };
      // eslint-disable-next-line no-undef
      var geoJ = L.geoJSON(geo);
      // eslint-disable-next-line no-undef
      var pgeo = L.Util.transform(geoJ, GZ2000, L.CRS.EPSG4326);
      pgeo.features[0].geometry.properties = {
        name: item.key,
      };

      // eslint-disable-next-line no-undef
      L.geoJSON(pgeo.features[0].geometry, {
        onEachFeature: (_, layer) => {
          layer.on({
            click: (e) => {
              getFeatureDetail(e.target.feature.geometry.properties.name);
            }
          })
        },
        color: "blue",
        fillColor: "rgb(123,180,255)",
        fillOpacity: 0.5,
      }).addTo(window.map);
    })
  }).then(() => {
  })
}

const initialized = () => {
  updateParams.uuid = getGUID();

  getYSFields().then((res) => {
    options.value = res.data;
    // 正则表达式剔除options.value.caption字段不包含中文的对象
    options.value = options.value.filter((item) => {
      // return item.caption.match(/[\u4e00-\u9fa5]/g) !== null && item.caption !== '工程编号' && item.caption !== '完成时间';
      if (YanshouMap[item.name]) {
        item.caption = YanshouMap[item.name];
        // 不显示没有中文的字段
        return item
      }
      // 如果是工程编号或者完成时间则不显示
      // return item.name !== 'gcbh' && item.name !== 'wcsj';

    });

    getJieDaoZ().then((res) => {
      jiezhen.value = res.data;
    });

    getQueryOperationEnumList().then(res => {
      // console.log(res);
      operations.value = res.data.data;
    })

    loadTableData();
  });


};

const isShowAdvSearch = ref(false);
const handleOnSearchFields = (field, val) => {
  console.log('查询', field, val);
  if (field && val) {
    getSearchList({
      field: field,
      value: val,
      table_name: pageName
    }).then(res => {
      fieldOptions.value = res.data.data;
      console.log(fieldOptions.value)
    })
  }
};

const getTypeOfField = (field) => {
  return options.value.find(item => item.name === field)?.type;
}

const handleOnDeleteField = (index) => {
  searchQurry.field_map_operates.splice(index+1, 1);
};

const handleOnAddFields = () => {
  searchQurry.field_map_operates.push({
    field: '',
    operate: '',
    value: ''
  });
}

const handleOnStatistic = () => {
  if (tableData.value.length === 0) {
    ElMessage.error('暂无数据');
    return;
  }
  store.setSearchParams(searchQurry);
  store.toggleShowStatistics();
}

const handleOnExportTable = () => {
  exportProjectResultExcel(searchQurry).then(res => {
    console.log(res);
    const link = document.createElement('a');
    try {
      let blob = new Blob([res.data]);
      let _fileName = '导出台账.xlsx';
      console.log(res.headers['content-disposition'])
      link.style.display = 'none';
      const url = window.URL || window.webkitURL || window.moxURL;
      link.href = url.createObjectURL(blob);
      link.setAttribute('download', _fileName.substring(_fileName.lastIndexOf('_') + 1));
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      url.revokeObjectURL(link.href);//销毁url对象
    }
    catch (e) {
      console.log(e);
    }
  })
}

const handleOnRowClick = (row) => {
  window.map.eachLayer(function (layer) {
    if (layer.feature && layer.feature.geometry.properties.name === row.smid) {
      window.map.fitBounds(layer.getBounds());
    }
  });
}

const handleOnSortChange = (data) => {
  console.log(data);
  searchQurry.field_map_operates = searchQurry.field_map_operates.filter((item) => item.operate !== 'orderAsc' && item.operate !== 'orderDesc');
  if (data.order == 'ascending') {
    console.log('orderAsc')
    searchQurry.field_map_operates.push({
      field: data.prop,
      operate: 'orderAsc',
      value: data.prop
    })
  }
  if (data.order == 'descending') {
    console.log('orderDesc')

    searchQurry.field_map_operates.push({
      field: data.prop,
      operate: 'orderDesc',
      value: data.prop
    })
  }
  console.log(searchQurry);
  loadTableData(false);
}

const handleOnOpenAdv = () => {
  isShowAdvSearch.value = !isShowAdvSearch.value;
  if (isShowAdvSearch.value && searchQurry.field_map_operates.length === 0) {
    searchQurry.field_map_operates.push({
      field: '',
      operate: '',
      value: ''
    });

  }
}
onMounted(() => {
  initialized();
})
</script>
<style>
.el-tabs__content {
  margin-top: -18px !important;
}
</style>
<style scoped>
.search-head {
  position: relative;
  font-size: 16px;
}

.adv-search {
  position: absolute;
  z-index: 11;
  width: 95%;
  /*height: 200px;*/
  left: 2.5%;
  top: 38px;
  background-color: white;
  box-shadow: inset 0px -1px 3px rgba(0, 0, 0, 0.2);
}

.xzqcxtj {
  background-color: white;
  box-shadow: inset 0px -1px 3px rgba(0, 0, 0, 0.2);
}

.xzqcxtj>div {
  margin: 5px;
  width: 214px;
  display: inline-block;
}

.xzqcxtj>div div {
  width: 210px;
  display: inline-block;
}

.search {
  width: 100px;
  font-size: 14px;
  color: black;
  text-align: center;
  line-height: 28px;
}
</style>
